import { createSlice } from "@reduxjs/toolkit";
import {request} from '@/utils'
import {setToken as _setToken,getToken,removeToken} from '@/utils'
import { loginApi,getProfileApi } from "@/apis/user";

const userStore = createSlice({
  name:'user',
  initialState:{
    // token:localStorage.getItem('token_key') || ''
    token:getToken() || '',
    userInfo:{}
  },
  reducers:{
    setToken(state,action){
      state.token = action.payload
      // localStorage.setItem('token_key',action.payload)
      _setToken(action.payload)
    },
    setUserInfo(state,action){
      state.userInfo = action.payload
    },
    clearUserInfo(state,action){
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  }
})

//解构出actionCreater
const {setToken,setUserInfo,clearUserInfo} = userStore.actions

//获取reducer函数

const userReducer = userStore.reducer

//异步方法  获取token
const fetchLogin = (loginForm) =>{
  return async (dispatch) =>{
    const res = await loginApi(loginForm)

    dispatch(setToken(res.data.token))
  }
}
//获取个人用户信息
const fetchUserInfo = () =>{
  return async (dispatch) =>{
    const res = await getProfileApi()
    dispatch(setUserInfo(res.data))
  }
}



export {
  setToken,
  fetchLogin,
  fetchUserInfo,
  clearUserInfo
}

export default userReducer